package com.bzkj.basicinfo.service.receive.impl;

import com.bzkj.basicinfo.domain.receive.WmsReceiveOrderDetailEntity;
import com.bzkj.basicinfo.domain.receive.WmsReceiveOrderEntity;
import com.bzkj.basicinfo.domain.receive.WmsRejectRecordEntity;
import com.bzkj.basicinfo.mapper.receive.WmsReceiveOrderDetailMapper;
import com.bzkj.basicinfo.mapper.receive.WmsReceiveOrderMapper;
import com.bzkj.basicinfo.mapper.receive.WmsRejectRecordMapper;
import com.bzkj.basicinfo.service.inspect.WmsInspectTaskService;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.common.utils.StringUtils;
import com.bzkj.basicinfo.service.receive.WmsReceiveOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WMS收货管理服务实现类
 *
 *@author lixinyu
 * @date 2025-10-22
 */
@Service
public class WmsReceiveOrderServiceImpl implements WmsReceiveOrderService {

    @Autowired
    private WmsReceiveOrderMapper receiveOrderMapper;

    @Autowired
    private WmsReceiveOrderDetailMapper receiveDetailMapper;

    @Autowired
    private WmsRejectRecordMapper rejectRecordMapper;

    @Autowired
    private WmsInspectTaskService inspectTaskService;

    /**
     * 查询收货单列表（分页）
     */
    @Override
    public TableDataInfo getReceiveOrderList(WmsReceiveOrderEntity entity, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WmsReceiveOrderEntity> list = receiveOrderMapper.selectReceiveOrderList(entity);
        PageInfo<WmsReceiveOrderEntity> pageInfo = new PageInfo<>(list);

        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        dataTable.setRows(list);
        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }

    /**
     * 根据ID查询收货单详情（含明细）
     */
    @Override
    public AjaxResult getReceiveOrderDetail(Long id) {
        // 查询主表
        WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(id);
        if (order == null) {
            return AjaxResult.error("收货单不存在");
        }

        // 查询明细
        List<WmsReceiveOrderDetailEntity> detailList = receiveDetailMapper.selectReceiveDetailByOrderId(id);

        // 组装返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("detailList", detailList);

        return AjaxResult.success("查询成功", result);
    }

    /**
     * 创建收货单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createReceiveOrder(WmsReceiveOrderEntity entity, List<WmsReceiveOrderDetailEntity> detailList) {
        try {
            // 参数校验
            if (entity == null) {
                return AjaxResult.error("收货单信息不能为空");
            }
            if (detailList == null || detailList.isEmpty()) {
                return AjaxResult.error("收货单明细不能为空");
            }

            // 生成收货单号
            String receiveOrderNo = generateReceiveOrderNo();
            entity.setReceiveOrderNo(receiveOrderNo);
            entity.setOrderStatus("0"); // 0待收货
            entity.setCreateTime(new Date());

            // 计算总数量
            BigDecimal totalQuantity = BigDecimal.ZERO;
            for (WmsReceiveOrderDetailEntity detail : detailList) {
                totalQuantity = totalQuantity.add(detail.getPlanQuantity());
            }
            entity.setTotalQuantity(totalQuantity);
            entity.setReceivedQuantity(BigDecimal.ZERO);
            entity.setRejectedQuantity(BigDecimal.ZERO);

            // 插入主表
            int rows = receiveOrderMapper.insertReceiveOrder(entity);
            if (rows <= 0) {
                return AjaxResult.error("创建收货单失败");
            }

            // 插入明细
            Long orderId = entity.getId();
            int lineNo = 1;
            for (WmsReceiveOrderDetailEntity detail : detailList) {
                detail.setReceiveOrderId(orderId);
                detail.setReceiveOrderNo(receiveOrderNo);
                detail.setLineNo(lineNo++);
                detail.setDetailStatus("0"); // 0待收货
                detail.setReceivedQuantity(BigDecimal.ZERO);
                detail.setRejectedQuantity(BigDecimal.ZERO);
                detail.setCreateTime(new Date());
                receiveDetailMapper.insertReceiveDetail(detail);
            }

            return AjaxResult.success("创建收货单成功", receiveOrderNo);
        } catch (Exception e) {
            throw new RuntimeException("创建收货单异常：" + e.getMessage(), e);
        }
    }

    /**
     * PDA收货确认
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult confirmReceive(Long detailId, BigDecimal receivedQuantity,
                                     String batchCode, String productDate, String expDate, String operator) {
        try {
            // 参数校验
            if (detailId == null) {
                return AjaxResult.error("收货明细ID不能为空");
            }
            if (receivedQuantity == null || receivedQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                return AjaxResult.error("收货数量必须大于0");
            }
            if (StringUtils.isEmpty(batchCode)) {
                return AjaxResult.error("批次号不能为空");
            }

            // 查询明细
            WmsReceiveOrderDetailEntity detail = receiveDetailMapper.selectReceiveDetailById(detailId);
            if (detail == null) {
                return AjaxResult.error("收货明细不存在");
            }

            // 计算已收货数量
            BigDecimal currentReceived = detail.getReceivedQuantity();
            BigDecimal newReceived = currentReceived.add(receivedQuantity);

            // 检查是否超量
            if (newReceived.compareTo(detail.getPlanQuantity()) > 0) {
                return AjaxResult.error("收货数量超过计划数量");
            }

            // 更新明细
            int rows = receiveDetailMapper.updateReceiveDetailQuantity(
                detailId, newReceived, detail.getRejectedQuantity(), batchCode, productDate, expDate
            );

            if (rows <= 0) {
                return AjaxResult.error("更新收货数量失败");
            }

            // 判断明细是否完成
            if (newReceived.compareTo(detail.getPlanQuantity()) == 0) {
                receiveDetailMapper.updateDetailStatus(detailId, "2", "qualified"); // 2已收货
            } else {
                receiveDetailMapper.updateDetailStatus(detailId, "1", null); // 1部分收货
            }

            // 更新主表已收货数量
            updateOrderQuantity(detail.getReceiveOrderId());

            return AjaxResult.success("收货确认成功");
        } catch (Exception e) {
            throw new RuntimeException("收货确认异常：" + e.getMessage(), e);
        }
    }

    /**
     * PDA拒收操作
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult rejectReceive(Long detailId, BigDecimal rejectQuantity,
                                   String rejectReasonType, String rejectReasonDesc,
                                   String photoUrls, String operator) {
        try {
            // 参数校验
            if (detailId == null) {
                return AjaxResult.error("收货明细ID不能为空");
            }
            if (rejectQuantity == null || rejectQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                return AjaxResult.error("拒收数量必须大于0");
            }
            if (StringUtils.isEmpty(rejectReasonType)) {
                return AjaxResult.error("拒收原因类型不能为空");
            }

            // 查询明细
            WmsReceiveOrderDetailEntity detail = receiveDetailMapper.selectReceiveDetailById(detailId);
            if (detail == null) {
                return AjaxResult.error("收货明细不存在");
            }

            // 计算拒收数量
            BigDecimal currentRejected = detail.getRejectedQuantity();
            BigDecimal newRejected = currentRejected.add(rejectQuantity);

            // 检查是否超量
            BigDecimal totalProcessed = detail.getReceivedQuantity().add(newRejected);
            if (totalProcessed.compareTo(detail.getPlanQuantity()) > 0) {
                return AjaxResult.error("收货+拒收数量超过计划数量");
            }

            // 创建拒收记录
            WmsRejectRecordEntity rejectRecord = new WmsRejectRecordEntity();
            rejectRecord.setRejectNo(generateRejectNo());
            rejectRecord.setReceiveOrderId(detail.getReceiveOrderId());
            rejectRecord.setReceiveOrderNo(detail.getReceiveOrderNo());
            rejectRecord.setReceiveDetailId(detailId);
            rejectRecord.setProductId(detail.getProductId());
            rejectRecord.setProductName(detail.getProductName());
            rejectRecord.setBatchCode(detail.getBatchCode());
            rejectRecord.setRejectQuantity(rejectQuantity);
            rejectRecord.setRejectReasonType(rejectReasonType);
            rejectRecord.setRejectReasonDesc(rejectReasonDesc);
            rejectRecord.setPhotoUrls(photoUrls);
            rejectRecord.setRejectHandler(operator);
            rejectRecord.setRejectTime(new Date());
            rejectRecord.setHandleStatus("pending"); // pending待处理
            rejectRecord.setCreateBy(operator);
            rejectRecord.setCreateTime(new Date());

            int rows = rejectRecordMapper.insertRejectRecord(rejectRecord);
            if (rows <= 0) {
                return AjaxResult.error("创建拒收记录失败");
            }

            // 更新明细拒收数量
            receiveDetailMapper.updateReceiveDetailQuantity(
                detailId, detail.getReceivedQuantity(), newRejected, null, null, null
            );

            // 更新主表拒收数量
            updateOrderQuantity(detail.getReceiveOrderId());

            return AjaxResult.success("拒收操作成功", rejectRecord.getRejectNo());
        } catch (Exception e) {
            throw new RuntimeException("拒收操作异常：" + e.getMessage(), e);
        }
    }

    /**
     * 完成收货（更新收货单状态）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult completeReceive(Long id, String operator) {
        try {
            // 查询收货单
            WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(id);
            if (order == null) {
                return AjaxResult.error("收货单不存在");
            }

            // 检查是否所有明细都已处理
            List<WmsReceiveOrderDetailEntity> detailList = receiveDetailMapper.selectReceiveDetailByOrderId(id);
            for (WmsReceiveOrderDetailEntity detail : detailList) {
                BigDecimal processed = detail.getReceivedQuantity().add(detail.getRejectedQuantity());
                if (processed.compareTo(detail.getPlanQuantity()) < 0) {
                    return AjaxResult.error("还有明细未完成收货");
                }
            }

            // 更新收货单状态
            int rows = receiveOrderMapper.updateReceiveOrderStatus(id, "2", operator); // 2已收货
            if (rows <= 0) {
                return AjaxResult.error("更新收货单状态失败");
            }

            // 更新实际收货日期
            order.setActualReceiveDate(new Date());
            order.setUpdateBy(operator);
            order.setUpdateTime(new Date());
            receiveOrderMapper.updateReceiveOrder(order);

            return AjaxResult.success("收货完成");
        } catch (Exception e) {
            throw new RuntimeException("完成收货异常：" + e.getMessage(), e);
        }
    }

    /**
     * 修改收货单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateReceiveOrder(WmsReceiveOrderEntity entity) {
        // 查询收货单
        WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(entity.getId());
        if (order == null) {
            throw new RuntimeException("收货单不存在");
        }

        // 只有未收货状态才能修改
        if (!"0".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有未收货状态的收货单才能修改");
        }

        entity.setUpdateTime(new Date());
        return receiveOrderMapper.updateReceiveOrder(entity);
    }

    /**
     * 删除收货单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteReceiveOrder(Long id, String operator, String reason) {
        try {
            // 查询收货单
            WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(id);
            if (order == null) {
                return AjaxResult.error("收货单不存在");
            }

            // 只有待收货状态才能删除
            if (!"0".equals(order.getOrderStatus())) {
                return AjaxResult.error("只有待收货状态的收货单才能删除");
            }

            // 删除明细
            receiveDetailMapper.deleteReceiveDetailByOrderId(id);

            // 删除主表
            int rows = receiveOrderMapper.deleteReceiveOrderById(id);
            if (rows <= 0) {
                return AjaxResult.error("删除收货单失败");
            }

            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            throw new RuntimeException("删除收货单异常：" + e.getMessage(), e);
        }
    }

    /**
     * 提取收货单（状态：未收货 -> 已收货）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int extractReceive(Long id, String operator) {
        // 查询收货单
        WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(id);
        if (order == null) {
            throw new RuntimeException("收货单不存在");
        }

        // 只有未收货状态才能提取
        if (!"0".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有未收货状态的收货单才能提取");
        }

        // 更新状态为已收货
        return receiveOrderMapper.updateReceiveOrderStatus(id, "1", operator);
    }

    /**
     * 签字确认（状态：已验收 -> 已上架）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int signReceive(Long id, String operator) {
        // 查询收货单
        WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(id);
        if (order == null) {
            throw new RuntimeException("收货单不存在");
        }

        // 只有已验收状态才能签字
        if (!"2".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有已验收状态的收货单才能签字");
        }

        // 更新状态为已上架
        return receiveOrderMapper.updateReceiveOrderStatus(id, "3", operator);
    }

    /**
     * 作废收货单（状态 -> 已作废）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelReceive(Long id, String operator) {
        // 查询收货单
        WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(id);
        if (order == null) {
            throw new RuntimeException("收货单不存在");
        }

        // 只有未收货状态才能作废
        if (!"0".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有未收货状态的收货单才能作废");
        }

        // 更新状态为已作废
        return receiveOrderMapper.updateReceiveOrderStatus(id, "4", operator);
    }

    // ========== 私有辅助方法 ==========

    /**
     * 生成收货单号
     */
    private String generateReceiveOrderNo() {
        return "RCV" + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
    }

    /**
     * 生成拒收单号
     */
    private String generateRejectNo() {
        return "REJ" + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
    }

    /**
     * 更新主表收货数量和拒收数量
     */
    private void updateOrderQuantity(Long orderId) {
        List<WmsReceiveOrderDetailEntity> detailList = receiveDetailMapper.selectReceiveDetailByOrderId(orderId);

        BigDecimal totalReceived = BigDecimal.ZERO;
        BigDecimal totalRejected = BigDecimal.ZERO;

        for (WmsReceiveOrderDetailEntity detail : detailList) {
            totalReceived = totalReceived.add(detail.getReceivedQuantity());
            totalRejected = totalRejected.add(detail.getRejectedQuantity());
        }

        receiveOrderMapper.updateReceiveQuantity(orderId, totalReceived, totalRejected);

        // 如果所有明细都已收货，更新主表状态
        WmsReceiveOrderEntity order = receiveOrderMapper.selectReceiveOrderById(orderId);
        BigDecimal totalProcessed = totalReceived.add(totalRejected);
        if (totalProcessed.compareTo(order.getTotalQuantity()) >= 0) {
            receiveOrderMapper.updateReceiveOrderStatus(orderId, "2", null); // 2已收货
        } else if (totalProcessed.compareTo(BigDecimal.ZERO) > 0) {
            receiveOrderMapper.updateReceiveOrderStatus(orderId, "1", null); // 1收货中
        }
    }

    /**
     * 确认已到货（状态：未收货 -> 已到货，并创建验收任务）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult confirmArrival(Long id, String operator) {
        try {
            // 1. 查询收货单
            WmsReceiveOrderEntity receiveOrder = receiveOrderMapper.selectReceiveOrderById(id);
            if (receiveOrder == null) {
                return AjaxResult.error("收货单不存在");
            }

            // 2. 验证状态，必须是未收货状态（0）
            if (!"0".equals(receiveOrder.getOrderStatus())) {
                return AjaxResult.error("只有未收货状态的单据才能确认到货，当前状态：" + receiveOrder.getOrderStatus());
            }

            // 3. 更新收货单状态为已到货（1）
            WmsReceiveOrderEntity updateOrder = new WmsReceiveOrderEntity();
            updateOrder.setId(id);
            updateOrder.setOrderStatus("1"); // 已到货
            updateOrder.setActualReceiveDate(new Date());
            updateOrder.setReceiveTime(new Date());
            updateOrder.setReceiver(operator);
            updateOrder.setUpdateBy(operator);
            updateOrder.setUpdateTime(new Date());

            int rows = receiveOrderMapper.updateReceiveOrder(updateOrder);
            if (rows <= 0) {
                return AjaxResult.error("更新收货单状态失败");
            }

            // 4. 同时创建验收任务
            try {
                Long inspectTaskId = inspectTaskService.createInspectTaskForReceiveOrder(
                    id,
                    receiveOrder.getReceiveOrderNo(),
                    operator
                );

                return AjaxResult.success("确认到货成功，已创建验收任务", inspectTaskId);
            } catch (Exception e) {
                // 如果创建验收任务失败，抛出异常回滚整个事务
                throw new RuntimeException("创建验收任务失败：" + e.getMessage(), e);
            }

        } catch (Exception e) {
            return AjaxResult.error("确认到货失败：" + e.getMessage());
        }
    }
}
